<template>
  <div class="tenant-selector">
    <!-- 超级管理员显示 -->
    <div v-if="isSuperAdmin" class="super-admin-badge">
      <a-tag color="gold" size="large">
        <template #icon>
          <Icon icon="mdi:crown" />
        </template>
        超级管理员
      </a-tag>
    </div>

    <!-- 学校管理员租户选择 -->
    <div v-else-if="isSchoolAdmin" class="school-admin-selector">
      <a-select
        v-model="selectedTenantId"
        :placeholder="placeholder"
        :loading="isLoading"
        :disabled="disabled"
        :options="tenantOptions"
        :allow-clear="allowClear"
        :size="size"
        @change="handleTenantChange"
        @clear="handleClear"
      >
        <template #prefix>
          <Icon icon="mdi:school" />
        </template>
        <template #option="{ data }">
          <div class="tenant-option">
            <div class="tenant-name">{{ data.label }}</div>
            <div class="tenant-status">
              <a-tag :color="getStatusColor(data.status)" size="small">
                {{ getStatusText(data.status) }}
              </a-tag>
            </div>
          </div>
        </template>
      </a-select>

      <!-- 租户信息显示 -->
      <div v-if="currentTenant && showTenantInfo" class="tenant-info">
        <a-card size="small" :bordered="false">
          <template #title>
            <div class="tenant-card-title">
              <Icon icon="mdi:school" />
              <span>{{ currentTenant.name }}</span>
            </div>
          </template>
          <div class="tenant-details">
            <div v-if="currentTenant.description" class="detail-item">
              <span class="label">描述：</span>
              <span class="value">{{ currentTenant.description }}</span>
            </div>
            <div v-if="currentTenant.address" class="detail-item">
              <span class="label">地址：</span>
              <span class="value">{{ currentTenant.address }}</span>
            </div>
            <div v-if="currentTenant.contactPhone" class="detail-item">
              <span class="label">联系电话：</span>
              <span class="value">{{ currentTenant.contactPhone }}</span>
            </div>
          </div>
        </a-card>
      </div>
    </div>

    <!-- 无权限状态 -->
    <div v-else class="no-permission">
      <a-alert type="warning" message="权限不足" description="您没有管理任何租户的权限，请联系系统管理员。" show-icon />
    </div>
  </div>
</template>

<script setup lang="ts">
import { Message } from '@arco-design/web-vue';
import { Icon } from '@iconify/vue';
import { computed, ref, watch, onMounted } from 'vue';

import { useUserStore } from '@/stores/user';
import type { TenantInfo } from '@/types/permission';
import { AdminType } from '@/types/permission';

// Props 定义
interface Props {
  placeholder?: string;
  disabled?: boolean;
  allowClear?: boolean;
  size?: 'mini' | 'small' | 'medium' | 'large';
  showTenantInfo?: boolean;
  autoLoad?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  placeholder: '选择要管理的学校',
  disabled: false,
  allowClear: true,
  size: 'medium',
  showTenantInfo: true,
  autoLoad: true
});

// Emits 定义
interface Emits {
  (e: 'change', tenant: TenantInfo | null): void;
  (e: 'clear'): void;
}

const emit = defineEmits<Emits>();

// 状态管理
const userStore = useUserStore();
const selectedTenantId = ref<string>();
const isLoading = ref(false);

// 计算属性
const isSuperAdmin = computed(() => userStore.isSuperAdmin);
const isSchoolAdmin = computed(() => userStore.isSchoolAdmin);
const currentTenant = computed(() => userStore.currentTenant);
const accessibleTenants = computed(() => userStore.accessibleTenants);

// 租户选项
const tenantOptions = computed(() =>
  accessibleTenants.value.map((tenant) => ({
    label: tenant.name,
    value: tenant.id,
    ...tenant
  }))
);

// 监听当前租户变化
watch(
  () => userStore.currentTenant,
  (tenant) => {
    selectedTenantId.value = tenant?.id;
  },
  { immediate: true }
);

// 方法定义
const handleTenantChange = async (tenantId: string) => {
  if (!tenantId) return;

  try {
    isLoading.value = true;
    await userStore.switchTenant(tenantId);
    const newTenant = accessibleTenants.value.find((t) => t.id === tenantId);
    emit('change', newTenant || null);
    Message.success('切换学校成功');
  } catch (error) {
    console.error('切换租户失败:', error);
    Message.error('切换学校失败，请重试');
    // 恢复之前的选择
    selectedTenantId.value = userStore.currentTenant?.id;
  } finally {
    isLoading.value = false;
  }
};

const handleClear = () => {
  selectedTenantId.value = undefined;
  emit('clear');
};

const getStatusColor = (status: string): string => {
  const colorMap: Record<string, string> = {
    active: 'green',
    inactive: 'orange',
    suspended: 'red'
  };
  return colorMap[status] || 'gray';
};

const getStatusText = (status: string): string => {
  const textMap: Record<string, string> = {
    active: '正常',
    inactive: '未激活',
    suspended: '已暂停'
  };
  return textMap[status] || '未知';
};

// 加载可用租户
const loadAvailableTenants = async () => {
  if (!isSchoolAdmin.value) return;

  try {
    isLoading.value = true;
    await userStore.fetchAvailableTenants();
  } catch (error) {
    console.error('加载租户列表失败:', error);
    Message.error('加载学校列表失败');
  } finally {
    isLoading.value = false;
  }
};

// 组件挂载时自动加载
onMounted(() => {
  if (props.autoLoad && isSchoolAdmin.value) {
    loadAvailableTenants();
  }
});

// 暴露方法给父组件
defineExpose({
  loadAvailableTenants,
  switchTenant: handleTenantChange,
  clear: handleClear
});
</script>

<style scoped lang="less">
.tenant-selector {
  .super-admin-badge {
    display: flex;
    align-items: center;

    .arco-tag {
      font-weight: 500;
    }
  }

  .school-admin-selector {
    .arco-select {
      min-width: 200px;
    }

    .tenant-option {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;

      .tenant-name {
        flex: 1;
        font-weight: 500;
      }

      .tenant-status {
        flex-shrink: 0;
        margin-left: 8px;
      }
    }

    .tenant-info {
      margin-top: 16px;

      .tenant-card-title {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 14px;
        font-weight: 500;
      }

      .tenant-details {
        .detail-item {
          display: flex;
          margin-bottom: 8px;
          font-size: 13px;

          .label {
            min-width: 80px;
            color: var(--color-text-2);
            font-weight: 500;
          }

          .value {
            flex: 1;
            color: var(--color-text-1);
          }

          &:last-child {
            margin-bottom: 0;
          }
        }
      }
    }
  }

  .no-permission {
    .arco-alert {
      border-radius: 6px;
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .tenant-selector {
    .school-admin-selector {
      .arco-select {
        min-width: 150px;
      }

      .tenant-info {
        margin-top: 12px;

        .tenant-details {
          .detail-item {
            flex-direction: column;
            align-items: flex-start;

            .label {
              min-width: auto;
              margin-bottom: 2px;
            }
          }
        }
      }
    }
  }
}
</style>
